import { history } from 'umi';
import ep from '@/utils/eventproxy';
import { clearLoginAfter } from '@/events/rxEvent';
import Cookies from 'js-cookie';
import storejs from 'storejs';
import api from '@/network/api';

const {
  userApi: { getUserinfo, clearLogin },
} = api;

let initState = () => ({
  //权限
  authority: [],

  // 用户信息
  user: {
    userId: '',
    name: '',
    orgId: '',
    orgList: '',
    telNum: '',
    empNum: '',
    username: '',
  },

});
// 这里主要是让子项目获取到默认值
window.masterUserState = initState();

export default {
  namespace: 'user',
  state: { ...initState() },
  effects: {
    // 获取用户信息
    *getUserinfo({ payload }, { call, put }) {
      // 走接口查询用户信息 （这里直接假设已经有数据）
      var authority = ['login']
      yield put({
        type: 'user/setState',
        payload: {
          user: {
            userId: '212321',
            name: 'admin',
            username: 'admin',
          },
          authority: authority,
        },
      });
    },

    // 退出登录
    *clearLogin({ payload }, { call, put, select }) {
      const { userId } = yield select(state => state.user.user);
      if (userId) clearLogin({ params: {}, body: { userId: userId } });
      yield put({ type: 'initAll', payload: {} });
      storejs.remove('token');
      storejs.remove('userId');
      storejs.remove('role');
      Cookies.remove('userId');
      clearLoginAfter.next();
      history.replace('/user/login');
    },

    // models 初始化
    *initAll({ payload }, { call, put }) {
      yield put({ type: 'init' });
      yield put({ type: 'masterGlobal/init' });
    },
  },

  reducers: {
    setState(state, action) {
      var value = { ...state, ...action.payload };
      ep.emit('masterStateChange', {
        name: 'user',
        type: 'setState',
        value: value,
      });
      return value;
    },
    init(state, action) {
      var value = { ...initState(), ...action.payload };
      ep.emit('masterStateChange', {
        name: 'user',
        type: 'init',
        value: value,
      });
      return value;
    },
  },
};